package com.example.filepersistencetest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.lang.StringBuilder

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //filePersistence
//        val inputText = load()
//        if (inputText.isNotEmpty()) {
//            editText.setText(inputText)
//            editText.setSelection(inputText.length)
//            Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show()
//        }

        //SharedPreferences
        saveButton.setOnClickListener {
            val edit = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
            edit.putString("name","Tom")
            edit.putInt("age",28)
            edit.putBoolean("married" +
                    "",false)
            edit.apply()
        }

        restoreButton.setOnClickListener {
            val sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE)
            val name = sharedPreferences.getString("name", "")
            val age = sharedPreferences.getInt("age", 0)
            val married = sharedPreferences.getBoolean("married", false)
            Log.d("MainActivity","name is $name")
            Log.d("MainActivity","age is $age")
            Log.d("MainActivity","married is $married")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val inputString = editText.text.toString()
        save(inputString)
    }

    private fun load(): String {
        val content = StringBuilder()
        try {
            val input = openFileInput("data")
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content.toString()
    }

    private fun save(inputText: String) {
        try {
            Log.d("MainActivity", "enter writer")
            val openFileOutput = openFileOutput("data", Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(openFileOutput))
            writer.use {
                it.write(inputText)
            }
            Log.d("MainActivity", "end writer")
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}